<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>基本资料</span>
      </div>
      <el-form :model="userInfo" ref="FormRef" :rules="rules" label-width="100px">
        <el-form-item label="登录名称">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item prop="nickname" label="用户昵称">
          <el-input v-model="userInfo.nickname"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="用户邮箱">
          <el-input v-model="userInfo.email"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateUserInfo">提交修改</el-button>
          <el-button @click="resetUserInfo">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { updateUserInfoAPI } from '@/api'
export default {
  data () {
    return {
      userInfo: {
        id: this.$store.state.userInfo.id,
        user_pic: '',
        username: this.$store.state.userInfo.username,
        nickname: '',
        email: ''
      },
      rules: {
        nickname: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '昵称必须是1-10位的非空字符串', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updateUserInfo () {
      this.$refs.FormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await updateUserInfoAPI(this.userInfo)
          if (res.code !== 0) return this.$message.error('更新用户信息失败!')
          this.$message.success('更新成功')
          this.$store.dispatch('initUserInfo')
        } else {
          return false
        }
      })
    },
    resetUserInfo () {
      this.$refs.FormRef.resetFields()
    }
  }
}
</script>
<style lang="less" scoped>
.el-form {
  width: 500px;
}

span {
  font-size: 18px;
}
</style>
